package com.lottery.football.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;
import org.springframework.stereotype.Service;

import com.lottery.football.customTags.Font;
import com.lottery.football.pojo.Dopester;
import com.lottery.football.pojo.Order;
import com.lottery.football.service.OrderService;
import com.lottery.football.service.PredictionService;
import com.lottery.football.util.Constants;
import com.lottery.football.util.ContentParser;
import com.lottery.football.util.PropertiesUtil;
import com.lottery.football.util.Spiders;
import com.lottery.football.util.StringUtil;

@Service(value="orderService")
public class OrderServiceImpl implements OrderService
{
	@Resource(name="predictionService")
	private PredictionService predictionService;
	
	/**
	 * 从个人主页中获得第一页历史订单，再从分页信息中获得总页数及剩余历史订单的ajax url
	 * 
	 * @param home page url like http://space.500.com/342iocrp/
	 * @return List<Order>
	 */
	@Override
	public List<Order> getAllOrders(Dopester dopester)
	{
		List<Order> orders = new ArrayList<Order>();
		String sfcHistoryUrl = dopester.getHomePage() + Constants.HISTORY_PAGE_SURFIX;
		String html = Spiders.get(sfcHistoryUrl);
		TableTag table = ContentParser.parseTag(html, TableTag.class, "class", "user_fa");
		if (table == null)
		{
			return null;
		}
		
		//TODO 分析分页信息，获取ajax url和总页数，
		int maxPageNo = 5;
		
		//TODO 读取最后保存的paymakeid, 若查到数据库中已有paymakeid，返回
		String paymakeId = "";
		
		// http://space.500.com/ajax/ajaxhistory.php?m=history&a=historyquan&uid=UID&lotid=1&playid=1&u=NAME&seltype=0&pageno=PAGENO
		// 方便起见 max page no. 设为5
		String ajaxUrl = PropertiesUtil.get("history.ajax.url").replace("UID", dopester.getUid()).replace("NAME", dopester.getCnName());
		for (int i=1; i <= maxPageNo; i++)
		{
			if (!this.getOrdersByAjax(ajaxUrl.replace("PAGENO", i + ""), paymakeId, orders))
			{
				break;
			}
		}
		
		return orders;
	}

	/**
	 * 
	 * @param ajaxUrl
	 * @param lasstPaymakeId
	 * @return false--新的记录已经读取完
	 */
	private boolean getOrdersByAjax(String ajaxUrl, String lastPaymakeId, List<Order> orders)
	{
		// url = "http://space.500.com/ajax/ajaxhistory.php?m=history&a=historyquan&uid=493836&lotid=1&playid=1&u=长远利益&seltype=0&pageno=1";
		String jsonData = Spiders.get(ajaxUrl);
		int startIndex = jsonData.indexOf("<div");
		int endIndex = jsonData.lastIndexOf("\"");
		// 去掉转义符  \" --> ", \/ --> /
		String html = jsonData.substring(startIndex, endIndex).replaceAll("\\\\\"", "\"").replaceAll("\\\\/", "/").replaceAll("\\\\r\\\\n", "");
		// System.out.println(html);
		TableTag table = ContentParser.parseTag(html, TableTag.class, "class", "user_fa");
		
		return getOrdersFromTable(table, lastPaymakeId, orders);
		
	}
	
	/**
	 * get order info from table tag
	 * @param table
	 * @return false--新的记录已经读取完
	 */
	private boolean getOrdersFromTable(TableTag table, String lastPaymakeId, List<Order> orders)
	{
		NodeList trList = table.searchFor(org.htmlparser.tags.TableRow.class, false);
		// System.out.println("-----tr size : " + trList.size());
		SimpleNodeIterator it = trList.elements();
		if (it.hasMoreNodes())
		{
			it.nextNode(); //第一行为table header，忽略
		}
		while(it.hasMoreNodes()){
			TableRow tr = (TableRow) it.nextNode();
			NodeList tdList = tr.searchFor(TableColumn.class, false);
			
			LinkTag link = (LinkTag) ((TableColumn) tdList.elementAt(7)).childAt(0);
			String paymakeUrl = link.getAttribute("href");
			String paymakeId = paymakeUrl.substring(paymakeUrl.lastIndexOf("paymakeid=") + 10, paymakeUrl.lastIndexOf("&"));
			if (lastPaymakeId.equals(paymakeId))
			{
				return false; //不再读取下一页
			}
			System.out.println(paymakeUrl);
			System.out.println(paymakeId);
			predictionService.getPredictionFile(paymakeUrl);
			
			String issueNo = ((TableColumn)tdList.elementAt(1)).getStringText(); // 期号
			String type = ((TableColumn)tdList.elementAt(2)).getStringText(); // 方案类型
			//String amount = ((TableColumn)tdList.elementAt(3)).getStringText(); // 方案金额
			//String reward = ((TableColumn)tdList.elementAt(4)).getStringText(); // 税前奖金
			//String status = ((Font)link.searchFor(Font.class, false).elementAt(0)).getStringText();
			String status = null;
			NodeList fontList = link.searchFor(Font.class, false);
			if (fontList == null || fontList.size() == 0)
			{
				status = link.getStringText();
			}
			else
			{
				status = ((Font)(link.searchFor(Font.class, false).elementAt(0))).getStringText();
			}
			
			Order order = new Order();
			order.setIssueNo(Integer.parseInt(issueNo));
			order.setPaymakeId(paymakeId);
			order.setUrl(paymakeUrl);
			order.setType(Constants.getOrderTypeMap().get(StringUtil.ascii2native(type)));
			order.setStatus(Constants.getOrderStatusMap().get(StringUtil.ascii2native(status)));
			order.setCreateDate(new Date());
			
			orders.add(order);
		}
		
		return true; //返回true继续获取下一页
	}

}
